import { NextRequest, NextResponse } from 'next/server'
import { getTools, getReviews, getFavorites, addTool, getCategories } from '@/lib/database'
import { optionalAuth, requireAuth, withErrorHandling } from '@/lib/auth-middleware'
import { toolValidation, validateInput } from '@/lib/validation'
import { randomUUID } from 'crypto'

// 获取工具列表
export const GET = withErrorHandling(async (request: NextRequest) => {
  return optionalAuth(request, async (req) => {
    const { searchParams } = new URL(request.url)

    // 验证搜索参数
    const searchValidation = validateInput(toolValidation.search, {
      q: searchParams.get('q') || '',
      category: searchParams.get('category') || undefined,
      page: searchParams.get('page') || '1',
      limit: searchParams.get('limit') || '20',
      sortBy: searchParams.get('sortBy') || 'createdAt',
      sortOrder: searchParams.get('sortOrder') || 'desc'
    })

    if (!searchValidation.success) {
      return NextResponse.json(
        { error: '搜索参数无效', details: searchValidation.errors },
        { status: 400 }
      )
    }

    const { q: query, category, page, limit, sortBy, sortOrder } = searchValidation.data
    const userId = searchParams.get('userId') || '' // 用于获取用户自己的工具
    const includeOwn = searchParams.get('includeOwn') === 'true' // 是否包含自己的工具

    const tools = await getTools(request)
    const reviews = await getReviews()
    const favorites = await getFavorites()
    const categories = await getCategories()

    // 创建分类映射
    const categoryMap = new Map(categories.map(cat => [cat.id, cat]))

    // 为每个工具添加统计信息
    const toolsWithCounts = tools.map(tool => {
      const toolReviews = reviews.filter(review => review.toolId === tool.id)
      const toolFavorites = favorites.filter(favorite => favorite.toolId === tool.id)

      // 计算平均评分
      const averageRating = toolReviews.length > 0
        ? toolReviews.reduce((sum, review) => sum + review.rating, 0) / toolReviews.length
        : 0

      // 确保分类信息正确
      const category = categoryMap.get(tool.categoryId)

      return {
        ...tool,
        category: category || {
          id: tool.categoryId,
          name: '未知分类',
          icon: '❓'
        },
        _count: {
          reviews: toolReviews.length,
          favorites: toolFavorites.length
        },
        averageRating: Math.round(averageRating * 10) / 10 // 保留一位小数
      }
    })

    // 根据权限过滤工具
    let filteredTools
    if (includeOwn && userId) {
      // 包含用户自己的工具（无论状态）+ 其他已审核的工具
      filteredTools = toolsWithCounts.filter(tool =>
        tool.status === 'APPROVED' || tool.userId === userId
      )
    } else {
      // 只返回已审核通过的工具（不需要部署状态）
      filteredTools = toolsWithCounts.filter(tool =>
        tool.status === 'APPROVED'
      )
    }

    // 搜索筛选
    if (query.trim()) {
      const searchQuery = query.toLowerCase().trim()
      filteredTools = filteredTools.filter(tool =>
        tool.title.toLowerCase().includes(searchQuery) ||
        tool.description.toLowerCase().includes(searchQuery) ||
        tool.category.name.toLowerCase().includes(searchQuery) ||
        tool.user.name.toLowerCase().includes(searchQuery)
      )
    }

    // 分类筛选
    if (category) {
      filteredTools = filteredTools.filter(tool => tool.categoryId === category)
    }

    // 按创建时间排序
    filteredTools.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())

    return NextResponse.json({
      success: true,
      data: filteredTools,
      total: filteredTools.length
    })
  })
})

// 提交新工具
export const POST = withErrorHandling(async (request: NextRequest) => {
  return requireAuth(request, async (req) => {
    console.log('POST /api/tools - 开始处理请求')
    const body = await request.json()
    console.log('POST /api/tools - 接收到的数据:', body)

    // 验证输入数据
    const validation = validateInput(toolValidation.create, body)
    if (!validation.success) {
      console.log('POST /api/tools - 数据验证失败:', validation.errors)
      return NextResponse.json(
        { error: '输入数据无效', details: validation.errors },
        { status: 400 }
      )
    }

    const validatedData = validation.data

    // 获取当前用户信息
    const user = req.user!
    console.log('POST /api/tools - 当前用户:', user.name)

    // 创建新工具对象 (只包含数据库需要的字段)
    const toolData = {
      title: validatedData.title,
      description: validatedData.description,
      url: validatedData.url,
      image: validatedData.image || '',
      categoryId: validatedData.categoryId,
      userId: user.id, // 使用当前登录用户
      status: 'PENDING' as const, // 默认状态为待审核
      isDeployed: false,
      deployPath: null,
      originalFile: ''
    }

    console.log('POST /api/tools - 准备保存工具:')
    console.log('  用户ID:', user.id)
    console.log('  用户名:', user.name)
    console.log('  工具标题:', toolData.title)

    // 保存工具
    const savedTool = await addTool(toolData)
    console.log('POST /api/tools - 工具保存成功:', savedTool.id)

    return NextResponse.json({
      success: true,
      data: savedTool,
      message: '工具提交成功，等待审核'
    })
  })
})
